package com.yunhe.authority.controller.wechat;

import com.yunhe.authority.domain.wechat.Code2Session;
import com.yunhe.authority.domain.wechat.EmployeeDTO;
import com.yunhe.authority.domain.wechat.KingKongDistrictDTO;
import com.yunhe.authority.domain.wechat.WechatLoginDTO;
import com.yunhe.authority.model.wechat.StationByDistanceVo;
import com.yunhe.authority.service.wechat.KingKongDistrictService;
import com.yunhe.authority.service.wechat.WechatService;
import com.yunhe.common.annotation.OperationRecord;
import com.yunhe.common.constant.SystemConsts;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UsernamePasswordException;
import com.yunhe.common.model.ResultObject;
import com.yunhe.common.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

/**
 * @desc 小程序登录Controller
 * @author zhengbo
 * @date 2021/2/2 16:14
 */
@Api(value = "WechatController", description = "微信小程序登录（企业用户）", tags = {"wechat"})
@RestController
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private WechatService wechatService;

    @Autowired
    private KingKongDistrictService kingKongDistrictService;

    /**
     * 微信换取session_key接口
     * @param js_code 登录凭证
     */
    @ApiOperation("微信换取session_key接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "js_code", value = "登录凭证", dataType = "String", paramType = "path"),
    })
    @RequestMapping(value = "/code2Session/{js_code}", method = RequestMethod.GET)
    public ResponseEntity<ResultObject<Code2Session>> code2Session(@PathVariable("js_code") String js_code) throws IOException, ArgumentErrorException {
        Code2Session code2Session = wechatService.getAuthInfo(js_code);
        return new ResponseEntity<>(new ResultObject<>(code2Session), HttpStatus.OK);
    }

    /**
     * 根据定位获取园区列表
     * @param longitude 经度
     * @param latitude 纬度
     */
    @ApiOperation("根据定位获取园区列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "longitude", value = "经度", dataType = "double", paramType = "query", required = false),
            @ApiImplicitParam(name = "latitude", value = "纬度", dataType = "double", paramType = "query", required = false)
    })
    @RequestMapping(value="/getParkByPosition", method = RequestMethod.POST)
    public ResponseEntity<ResultObject<List<StationByDistanceVo>>> getParkByPosition(@RequestParam(value = "longitude", required = false) Double longitude,
                                                                                        @RequestParam(value = "latitude", required = false) Double latitude) {
        List<StationByDistanceVo> result = wechatService.getStationByPosition(longitude, latitude);
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    /**
     * 微信端未登录查询园区下金刚区以及所有服务
     * @param parkId 虚拟园区id
     */
    @ApiOperation("微信端未登录查询园区下金刚区以及所有服务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parkId", value = "虚拟园区id", dataType = "Long", paramType = "query")
    })
    @RequestMapping(value = "/findMenusByParkId" ,method = RequestMethod.POST)
    public ResponseEntity<ResultObject<KingKongDistrictDTO>> findKingKongDistrict(@RequestParam(value = "parkId") Long parkId) {
        KingKongDistrictDTO result = kingKongDistrictService.findKingKongDistrictMenuByParkId(parkId, "1");
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    /**
     * 根据手机号和密码获得用户（执行登录）
     * @param phone 手机号
     * @param password 密码
     */
    @ApiOperation("根据用户名和密码获得用户（执行登录）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "js_code", value = "js_code", dataType = "String", paramType = "query")
    })
    @RequestMapping(value="/login", method = RequestMethod.POST)
    public ResponseEntity<ResultObject<WechatLoginDTO>> login(@RequestParam("password") String password,
                                                              @RequestParam("phone") String phone,
                                                              @RequestParam("js_code") String js_code)
            throws UsernamePasswordException, IOException, ArgumentErrorException, ObjectNotFoundException {
        Code2Session code2Session = wechatService.getAuthInfo(js_code);
        WechatLoginDTO result = wechatService.loginByPhoneAndPassword(phone, password, code2Session.getOpenid());
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    /**
     * 根据手机号和验证码获得用户（执行登录）
     * @param phone 键
     * @param verificationCode 值
     */
    @ApiOperation("根据手机号和验证码获得用户（执行登录）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "verificationCode", value = "验证码", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "js_code", value = "js_code", dataType = "String", paramType = "query")
    })
    @RequestMapping(value="/loginByVerificationCode", method = RequestMethod.POST)
    public ResponseEntity<ResultObject<WechatLoginDTO>> loginByVerificationCode(@RequestParam(value = "phone", required = true) String phone,
                                                                                @RequestParam(value = "verificationCode", required = true) String verificationCode,
                                                                                @RequestParam("js_code") String js_code)
            throws ArgumentErrorException, IOException, ObjectNotFoundException {
        Code2Session code2Session = wechatService.getAuthInfo(js_code);
        WechatLoginDTO result = wechatService.loginByPhoneAndVerificationCode(phone, verificationCode, code2Session.getOpenid());
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    /**
     * 忘记密码
     * @param phone 手机号
     * @param verificationCode 验证码
     * @param password 密码
     */
    @ApiOperation("忘记密码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "verificationCode", value = "验证码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/changePassword", method = RequestMethod.POST)
    @OperationRecord(menu = "忘记密码", actionType = SystemConsts.ACTION.EDIT, action = "忘记密码")
    public ResponseEntity<ResultObject> changePassword(@RequestParam("phone") String phone,
                                                       @RequestParam("verificationCode") String verificationCode,
                                                       @RequestParam("password") String password)
            throws ArgumentErrorException {
        if(StringUtil.isEmpty(verificationCode)){
            throw new ArgumentErrorException("请填写验证码");
        }
        wechatService.changePassword(phone, verificationCode, password);
        return new ResponseEntity<>(new ResultObject<>(), HttpStatus.OK);
    }

    /**
     * 切换账号(企业和园区)
     * @param employeeDTO 员工以及其信息
     */
    @ApiOperation("切换账号(企业和园区)")
    @RequestMapping(value = "/switchEnterprise", method = RequestMethod.POST)
    public ResponseEntity<ResultObject> switchEnterprise(@RequestBody EmployeeDTO employeeDTO) {
        wechatService.switchEnterprise(employeeDTO);
        return new ResponseEntity<>(new ResultObject<>(), HttpStatus.OK);
    }

    /**
     * 上传头像
     * @param phone 手机号
     * @param photoUrl 头像地址
     */
    @ApiOperation("上传头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "photoUrl", value = "头像地址", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST)
    public ResponseEntity<ResultObject> uploadPhoto(@RequestParam("phone") String phone,
                                                    @RequestParam("photoUrl") String photoUrl) {
        wechatService.uploadPhoto(phone, photoUrl);
        return new ResponseEntity<>(new ResultObject<>(), HttpStatus.OK);
    }
}
